package com.xy.tool.webmvc.exception;

import com.xy.lang.domain.Result;
import com.xy.lang.exception.ValidationException;
import com.xy.tool.util.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 *
 * @author zsp
 * @date 2019-11-30
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    public Result<?> handler(Exception e) {
        LogUtils.error(log, e.getMessage(), e);
        return Result.fail();
    }

    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public Result<?> handlerDuplicateKeyException(DuplicateKeyException e) {
        LogUtils.debug(log, "DuplicateKeyException: " + e.getMessage());
        return Result.success();
    }

    @ExceptionHandler(ValidationException.class)
    public Result handleValidationException(ValidationException e) {
        LogUtils.error(log, "ValidationException: " + e.getMessage());
        return Result.ofBadRequest(e.getMessage());
    }

}
